<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--<script type="text/javascript" src="<?php //echo base_url()?>js/elable_polygon.js"></script> -->
<script type="text/javascript" src="<?php echo base_url()?>js/elable_popup_polygon.js"></script>
<script type="text/javascript">

    var map; // global map place holder
    var map_network; 
    var marker; // global marker place holder (singular)
    var map_zoomlevel; // global map zoom level (integer)
    var map_network_zoomlevel; // global map network zoom level (integer)
    var show_polygons = 1; // global show polygon status (1 means polygon showed, 0 polygon destroyed)    
    var polygon_fetched = 0; // global status whether the polygon data has been fetched from database
    var network_polygons = []; // global array containing network polygons           
    var bounds = new Array(); ;
    var label_popup_polygon;
    var gmarkers = []; // for crime map marker
    var show_markers = 1; // global show marker status (1 means polygon showed, 0 polygon destroyed)
    var marker_fetched = 0; // global status whether the marker data has been fetched from database
    var label; // for label marker crime map
    /* Draw marker begin */
    function Label(opt_options) {
     // Initialization
     this.setValues(opt_options);

     // Label specific      
     var div = this.div_ = document.createElement('div');
     div.setAttribute('id','popup');          
     var div1 = document.createElement('div');
     var div2 = document.createElement('div');
     div1.setAttribute('id','div1');         
     
     div1.style.cssText = 'font-size:12px;line-height:16px;background:#FFFFFF;color:#820851;border: 1px solid #820851;width:160px;padding:3px 7px;';
     div2.setAttribute('id','div2');
     div2.style.cssText = 'font-size:11px;line-height:22px;font-weight:bold; background:#820851;color:#FFFFFF;padding:0 7px;';
     div.appendChild(div1);
     div.appendChild(div2);
     div.style.cssText = 'position: absolute; display: none; z-index:2000;';
    };
    
    Label.prototype = new google.maps.OverlayView;
    
    // Implement onAdd
    Label.prototype.onAdd = function() {
     //var pane = this.getPanes().overlayLayer;
     var pane = this.getPanes().floatPane;
     pane.appendChild(this.div_);

     // Ensures the label is redrawn if the text or position is changed.
     var me = this;
     this.listeners_ = [
       google.maps.event.addListener(this, 'mouseover',
           function() { me.draw(); }),
       google.maps.event.addListener(this, 'mouseout',
           function() { me.draw(); })
     ];
    };

    // Implement onRemove
    Label.prototype.onRemove = function() {
     this.div_.parentNode.removeChild(this.div_);

     // Label is removed from the map, stop updating its position/text.
     for (var i = 0, I = this.listeners_.length; i < I; ++i) {
       google.maps.event.removeListener(this.listeners_[i]);
     }
    }; 
    
    // Implement draw
    Label.prototype.draw = function() {
     var projection = this.getProjection();
     var position = projection.fromLatLngToDivPixel(this.get('position'));

     var div = this.div_;
     div.style.left = position.x + 'px';
     div.style.top = position.y + 'px';
     div.style.display = 'block';    
        
     document.getElementById('div1').innerHTML = this.get('text1').toString();
     document.getElementById('div2').innerHTML = this.get('text2').toString();
    };
    /* Draw marker end */ 
  $(document).ready(function(){
    // initialization on onload
    initialize();        
        $('#show_address_button').click(function(){
            //if ($("#newmapwrap").is(":visible")) {
                
                //$("#map").slideDown();
                
                //$(".open_panel").text("Close Panel");
            //} else {
                //$("#map").css({'height':'0px', 'overflow':'hidden'});
                //$("#newmapwrap").fadeIn('slow');
                //$(".open_panel").text("Open Panel");
                //$('#filter_submit').click(); 
            //}
            
            //setTimeout('codeAddress()', 1000);
            if ($("#province").val() == "") {
                $('#message').html('Province is required');
                //return false;
            }else{
                codeAddress();    
            }
            
            /*if($("#newmapwrap").is(":visible")) {                
                $("#newmapwrap").slideUp('slow');                 
            }else{
                $("#land_ads").slideUp('slow');                
            }
            
            $("#map").css({'width':'590px', 'height':'300px', 'overflow':''});*/
            return false;        
        });
        check_marker(1);

  }); // end onready
function check_polygon(map_zoomlevel){
  show_polygons = 1;
  /*if(map_zoomlevel > 6){
    if(show_polygons == 0){
    show_polygons = 1;
    }
    
  }else{

    show_polygons = 0;
  }*/
  // check if need to fetch poly
    if(show_polygons == 1){
      if(polygon_fetched == 0){
    fetch_polygon();
    polygon_fetched = 1;
      }else{
    $.each(network_polygons, function(i,item){
      item.setMap(map_network);
    });
      }
    }else{
      $.each(network_polygons, function(i,item){
    item.setMap(null);
      });
    }
}

function check_marker(map_network_zoomlevel){
  show_markers = 1;
  /*if(map_network_zoomlevel > 12){
    if(show_markers == 0){
    show_markers = 1;
    }
    
  }else{

    show_markers = 0;
  }*/
  // check if need to fetch poly
    if(show_markers == 1){
      if(marker_fetched == 0){
    fetch_marker();
    marker_fetched = 1;
      }else{
    $.each(gmarkers, function(i,item){
      item.setMap(map);
    });
      }
    }else{
      $.each(gmarkers, function(i,item){
    item.setMap(null);
      });
    }
}

function fetch_marker(){
  if(marker_fetched == 0){
    $.getJSON("<?php echo site_url('json_request/crime_marker_by_month')?>",function(data){
      $.each(data, function(i,item){    
    	  create_marker(item.latitude, item.longitude, item.icon , item.icon , item.crime_type_name , item.date , item.time,  item.crime_type , item.id );    
      });

    });      
    marker_fetched = 1;
  }else{
  }
}    
/* function undraw_polygons(polygon_undrawed){
  polygon_undrawed.setMap( null);
}

function undraw_markers(marker_undrawed){
  marker_undrawed.setMap( null);
} */
function fetch_polygon(){
  if(polygon_fetched == 0){
    $.getJSON("<?php echo site_url('json_request/network_polygon')?>",function(data){
      $.each(data, function(i,item){
    array_path = item.path.split('#');
    item.path = array_path;
    create_polygon(item, 1000 - i);
      });

    });      
    polygon_fetched = 1;
  }else{
  }
}
function initialize() {
    geocoder = new google.maps.Geocoder();

    var southAfrica = new google.maps.LatLng(-30.559482, 22.937506);
    var myOptions = {
    zoom: 5,
    center: southAfrica,
    mapTypeControlOptions: {
        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
    },
    navigationControlOptions: {
        style: google.maps.NavigationControlStyle.DEFAULT
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    map_network = new google.maps.Map(document.getElementById("map_network"), myOptions);    
    // Add dragging event listeners.
    google.maps.event.addListener(map_network, 'zoom_changed', function() {
      map_network_zoomlevel = map_network.zoom;
      check_polygon(map_network_zoomlevel);
    });
    google.maps.event.addListener(map_network, 'center_changed', function() {
      map_network_zoomlevel = map_network.zoom;
      check_polygon(map_network_zoomlevel);
    });
    
    google.maps.event.addListener(map, 'zoom_changed', function() {
      map_zoomlevel = map.zoom;
      check_marker(map_zoomlevel);
    });
    google.maps.event.addListener(map, 'center_changed', function() {
      map_zoomlevel = map.zoom;
      //check_marker(map_zoomlevel);
    });

}


function codeAddress() {
    var street_address = document.getElementById("address").value;
    var province = document.getElementById("province").value;
    var address = street_address+', '+province;
    var map_display;
    if ($("#map").is(":visible")) {               
        map_display = map;
    } else {
        map_display = map_network;
    }
    marker = new google.maps.Marker({
        position: myLatlng, 
        map: map_display,
        //draggable: true,
        title:"Incident Location",
        icon: '<?php echo base_url(); ?>image/point/pin_point.png',
        shadow: shadow  
    });
    var myLatlng = new google.maps.LatLng(-26.2, 28.08333);
    var shadow = new google.maps.MarkerImage('<?php echo base_url(); ?>image/point/pin_point_shadow.png');
    if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
            document.getElementById("message").innerHTML = '';
            if (status == google.maps.GeocoderStatus.OK) {
                map_display.setZoom(13);
                map_display.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);                
                if(results.length > 1){
                document.getElementById("message").innerHTML = "Found " +results.length +" results";
                    for (var i=0; i<results.length; i++) {                        
                        document.getElementById("message").innerHTML += "<br>" + (i+1) 
                        + ": <a href='javascript:map.setCenter(new google.maps.LatLng"
                        + results[i].geometry.location + "); marker.setPosition(new google.maps.LatLng" + results[i].geometry.location + ");'>" 
                        + results[i].formatted_address + "</a>";                        
                    }
                }
                // centre the map on the first result
                google.maps.event.trigger(map_display, 'resize'); // resize to full size 
                map_display.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);                
            } else {
                //document.getElementById("message").innerHTML += "Geocode was not successful for the following reason: " + status;
            	document.getElementById("message").innerHTML += "Error! Google Geocode reports Zero Results found Enter a City/Town to improve your results Or check the address details entered for errors";
            }
        });
    }
}

function hide_popup_polygon(){
    document.getElementById('div_network').style.display = 'none';    
}

function create_polygon(raw_poly_data, z_index){
  var poly_points = [];
  var bounds = new google.maps.LatLngBounds();
  $.each(raw_poly_data.path , function(i,point){
    point = point.replace(/\(|\)/g,"");
    point = point.split(",");
    point = new google.maps.LatLng(point[0], point[1]);
    poly_points.push(point);
    bounds.extend(point);
    
  });
  //map.fitBounds(bounds);

  var polygon_object = new google.maps.Polygon({
    paths: poly_points,
    strokeColor: "#ff8800",
    strokeOpacity: 0.8,
    strokeWeight: 1,
    fillColor: "#000000",
    fillOpacity: 0.1,
    zIndex: z_index
  });  
  
  var center_polygon = new google.maps.Marker({
        position: new google.maps.LatLng(bounds.getCenter().lat(), bounds.getCenter().lng()), 
        map: map_network,        
        icon: '<?php echo base_url(); ?>image/transparent.png',
        shadow: '<?php echo base_url(); ?>image/transparent.png' 
    });
  var header_popup = '<a href="<?php echo site_url('network')?>/' + raw_poly_data.slug_name + '">' +raw_poly_data.name+ '</a>';    
  var content_popup = '<a style="color:white" href="<?php echo site_url('network/join_network')?>/' + raw_poly_data.id + '">' +raw_poly_data.jumlah + ' Members - Join Now!</a>';
  google.maps.event.addListener(polygon_object, 'click', function(){
      window.location = "<?php echo site_url('network'); ?>/"+raw_poly_data.slug_name;
  });
  google.maps.event.addListener(polygon_object, 'mouseover', function(event){
	  clearTimeout(tOut);
      removeTheLabel();
      label_popup_polygon = new Label_popup_polygon({
          map: map_network
      });
    polygon_object.setOptions({fillColor : '#008000',strokeWeight: 2});
    //alert(polygon_object.zIndex);
        var bind_position = new google.maps.Marker({
            position: event.latLng, 
            map: map_network,
            icon: '<?php echo base_url(); ?>image/transparent.png',
            shadow: '<?php echo base_url(); ?>image/transparent.png'
        });
        if (document.getElementById('div_network') == null){
        	label_popup_polygon.bindTo('position', bind_position, 'position');
        	label_popup_polygon.set('text_network1', header_popup);
        	label_popup_polygon.set('text_network2', content_popup);
        }else {
            document.getElementById('div_network').style.display = 'block'; 
            label_popup_polygon.bindTo('position', bind_position, 'position');
            label_popup_polygon.set('text_network1', header_popup);
            label_popup_polygon.set('text_network2', content_popup);    
        } 
        tempLabel = label_popup_polygon;
        delete label_popup_polygon;
  });
  google.maps.event.addListener(polygon_object, 'mouseout', function(){
    polygon_object.setOptions({fillColor : '#000000',strokeWeight: 1});
    tOut = setTimeout(removeTheLabel, 5000);
  });

  polygon_object.setMap(map_network);
  network_polygons.push(polygon_object);
}

var tempLabel;     
var tOut;  

function removeTheLabel(){
    if (tempLabel != null){
        tempLabel.unbind('map');
        tempLabel.setMap(null);
        tempLabel = null;      
    }          
}

function create_marker(lat, lon, icon_image, icon_shadow, title, date, time, crime_type, crime_id){
    if(icon_shadow != null){
        var shadow_image = icon_shadow.split(".");    
    }else{
        var str = 'other.png';
        var shadow_image = str.split(".");
        //alert(shadow_image[0]);
    }
    //var temp_content = content.split(" ");
    var temp_content_one = date.split("-");
    var temp_date = temp_content_one[0] +"/"+temp_content_one[1]+"/"+ temp_content_one[2];
    //var temp_time = temp_content[1].substring(0,5);    
   
    var temp_time;
    //temp_time = time.split(" ");
    if(time.substring(0,7) == 'Unknown' ){
        temp_time = '';    
    }else{
        temp_time = ' at ' + time;    
    }
    //var real_content = temp_date + ' @ ' + temp_time + '<br /> <a style="color:white" href="<?php echo site_url('crime_report/detail')?>/' + crime_id + '"> > click for more</a>';    
    var real_content = '<a style="color:white" href="<?php echo site_url('crime_report/detail')?>/' + crime_id + '">' + temp_date + temp_time + ' >></a>';    
    var new_title = '<a onclick="goto_detail(this); return false;" href="<?php echo site_url('crime_report/detail')?>/' + crime_id + '">' + title + '</a>';
    var shadow = new google.maps.MarkerImage(
    '<?php echo base_url(); ?>image/point/'+shadow_image[0]+'_shadow.png',
        // The shadow image is larger in the horizontal dimension
        // while the position and offset are the same as for the main image.
        new google.maps.Size(49, 35),
        new google.maps.Point(0,0),
        new google.maps.Point(10, 35));
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon), 
        map: map,            
        //title:"Incident Location",
        icon: '<?php echo base_url(); ?>image/point/'+icon_image,
        shadow: shadow  
    });
    
    marker.mycategory = crime_type;                                 
    marker.myname = title;
    
    google.maps.event.addListener(marker, "mouseover", function() {
        clearTimeout(tOut);
        removeTheLabel();
        label = new Label({
                map: map
        }); 
        if (document.getElementById('popup') == null){
            
            //alert('here1');
            
            label.bindTo('position', marker, 'position');        
            label.set('text1', new_title);
            label.set('text2', real_content); 
        }else {
            document.getElementById('popup').style.display = 'block'; 

            label.bindTo('position', marker, 'position');        
            label.set('text1', new_title);
            label.set('text2', real_content);
            //document.getElementById('popup').style.display = 'block';
            //setTimeout(removeTheLabel, 5000);    
        } 
        tempLabel = label;
        delete label;
    });
    
    google.maps.event.addListener(marker, "mouseout", function() {  
        tOut = setTimeout(removeTheLabel, 5000);
    });
    
    gmarkers.push(marker);
}

$('#popup').mouseover(function() {
  clearTimeout(tOut);
});
$('#popup').mouseout(function() {
  tOut = setTimeout(removeTheLabel, 2000);
});

function hide_popup_marker(){
    document.getElementById('popup').style.display = 'none';    
}
</script>